<?php

namespace dexcedu;


use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Validation\Constraint\StrictValidAt;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Token\Parser;
use Lcobucci\JWT\Validation\Validator;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;


class Websocket
{
    // 模型对象
    protected $model;
    // 视图对象
    protected $secretKey;
    // 控制器类实例时,要确保模型和视图对象可用
    public function __construct($model, $secretKey)
    {
        $this->model = $model;
        $this->secretKey = $secretKey;
    }

    function validateJWT($jwt)
    {

        // 传入登陆密钥


        $data = $this->model->onfetch('*', 'dex_secretKey', 1, ['id' => $jwt])['data']['secretKey'];
        // 获取数据库
        if ($data) {
            $data = self::decryptData($data);
        } else {
            // 这里返回账号在其他地方登陆
            return '没登陆';
        }

        if ($data) {
            $parser = new Parser(new JoseEncoder());
            $token = $parser->parse($data);
            // 创建验证器
            $validator = new Validator();
            // 获取系统默认时区
            $systemTimezone = date_default_timezone_get();
            $timezone = new \DateTimeZone($systemTimezone);
            $time = new SystemClock($timezone);
            // 使用ValidAt约束验证令牌的时间范围

            if (!$validator->validate($token, new StrictValidAt($time)) || !$validator->validate($token, new SignedWith(new Sha256(), InMemory::plainText($token->claims()->get('password'))))) {
                // 令牌在时间范围之外
                return false;
            } else {
                // 考虑验证签名https://lcobucci-jwt.readthedocs.io/en/latest/validating-tokens/
                // 成功 返回用户账号密码
                $arr = ['username' => $token->claims()->get('username'), 'password' => $token->claims()->get('password')];
                $arr =  $this->model->onfetch('*', 'dex_user', 1, $arr);
                $newarr =  $this->model->onfetch('*', 'dex_UserGroup', 1, ['id' => $arr['data']['UserGroup']]);
                unset($newarr['data']['id']);
                $arr = array_merge($arr['data'], $newarr);
                return $arr;
            }
        } else {
            //账号登陆失效
            return false;
        }
    }
    // 解密
    function decryptData($encryptedData)
    {
        list($encryptedData, $iv) = explode('::', base64_decode($encryptedData), 2);
        return json_decode(openssl_decrypt($encryptedData, 'aes-256-cbc', $this->secretKey, 0, $iv), true);
    }
}
